package cn.afactory.tygz.ui.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;

import com.harwkin.nb.camera.callback.CameraImageListener;
import com.harwkin.nb.camera.model.PicsItem;
import com.harwkin.nb.camera.options.CameraOptions;
import com.harwkin.nb.camera.pop.CameraPop;
import com.harwkin.nb.camera.pop.CameraPopListener;
import com.harwkin.nb.camera.type.OpenType;

import java.util.ArrayList;
import java.util.List;

import cn.afactory.tygz.R;
import cn.afactory.tygz.common.ImageUploadType;
import cn.afactory.tygz.model.ImageInfo;
import cn.afactory.tygz.model.ImageInfoList;
import cn.afactory.tygz.model.UploadFileInfoList;
import cn.afactory.tygz.net.NetManager;
import cn.afactory.tygz.net.lsn.OnResponseListener;
import cn.afactory.tygz.ui.base.BaseFragment;
import cn.afactory.tygz.ui.base.adapter.SubjectImgGirdAdapter;
import cn.afactory.tygz.ui.base.thirdpart.pulltorefresh.PullToRefreshBase;
import cn.afactory.tygz.ui.base.thirdpart.pulltorefresh.PullToRefreshGridView;
import cn.afactory.tygz.ui.base.utils.ImageUtils;
import cn.afactory.tygz.ui.base.utils.LocalUtils;
import cn.afactory.tygz.ui.base.utils.NaviUtils;
import cn.afactory.tygz.ui.base.utils.SPUtils;
import cn.afactory.tygz.ui.base.utils.ScreenUtil;
import cn.afactory.tygz.ui.base.utils.sns.ViewListener;
import cn.afactory.tygz.ui.sns.controller.SnsControler;

public class MyAlbumsFragment extends BaseFragment {
    private static final String TAG = MyAlbumsFragment.class.getSimpleName();
    protected SnsControler mController;
    protected SubjectImgGirdAdapter mAdapter;
    private List<ImageInfo> mAlbums = new ArrayList<>();
    private LayoutInflater minflater;
    protected int mPageIndex = 1;
    protected int mPageSize = 10;
    private long mTargetUserId = -1;
    private String mUserName;
    public MyAlbumsFragment(long targetUserId,String userName) {
        mTargetUserId = targetUserId;
        mUserName = userName;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mController = new SnsControler(mContext, mUIHandler, null);
    }

    @Override
    public View onCreateViewCustom(LayoutInflater inflater, ViewGroup container) {
        this.minflater = inflater;
        View mlayout = inflater.inflate(R.layout.fg_my_albums, null);
        initViews(mlayout);
        if(SPUtils.isSelf(getActivity(),mTargetUserId)){
            setTitleText("我的相册");
        }else {
            if(mUserName == null){
                setTitleText("TA的私密相册");
            }else {
                setTitleText(mUserName + "的相册");
            }
        }
        if(SPUtils.isSelf(getActivity(),mTargetUserId)) {
            initCameraPop();
            setRightButton("上传照片", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    prepareUploadImages();
                }
            });
        }
        return mlayout;
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case SnsControler.MSG_GET_USER_ALBUMS_OK:
                if (msg.obj instanceof ImageInfoList) {
                    hideErrorPage(-1);
                    ImageInfoList t = (ImageInfoList) msg.obj;
                    if (t.data != null && t.data.size() >= 0) {
                        try {
                            mAlbums.addAll(t.data);
                            mAdapter.updateDatas(convertImageInfoToString(mAlbums));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        if (mAdapter.getCount() == 0) {
                            showNullPage(true);
                        }
                    }
                }
                break;
            case SnsControler.MSG_GET_USER_ALBUMS_KO:
                if (mAdapter.getCount() == 0) {
                    hideErrorPage(-1);
                    showErrorPage(msg.arg1, new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            startLoadData(true);
                        }
                    });
                } else {
                    LocalUtils.showToast(mContext, (String) msg.obj);
                }
                break;
        }

        // 结束下拉刷新
        if (plgridView.isRefreshing()) {
            plgridView.onRefreshComplete();
        }
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        startLoadData(true);
    }

    /**
     * 初始化组件 views
     *
     * @param view
     */
    private void initViews(View view) {
        plgridView = (PullToRefreshGridView) view.findViewById(R.id.plv_subject);
        initListView();
    }

    /**
     * 加载listview数据
     */
    protected void startLoadData(boolean cleanData) {
        if (cleanData) {
            mPageIndex = 1;
            mAlbums.clear();
        }

        mController.doGetUserAlbums(mTargetUserId);
    }

    /**
     * 初始化list view
     */
    private void initListView() {
        int width = (ScreenUtil.getScreenWidth(mContext) -
                mContext.getResources().getDimensionPixelOffset(R.dimen.margin_5dp) * 3 -
                mContext.getResources().getDimensionPixelOffset(R.dimen.margin_10dp) * 2) / 4;
        int height  = width + mContext.getResources().getDimensionPixelOffset(R.dimen.healthcircle_padding2);

        mAdapter = new SubjectImgGirdAdapter(mContext, convertImageInfoToString(mAlbums), width, height);
        plgridView.setAdapter(mAdapter);
        plgridView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        plgridView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
                startLoadData(true);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
                startLoadData(false);
            }
        });
        mAdapter.setListener(new ViewListener() {
            @Override
            public void onClick(int position, List<String> mPath) {
                NaviUtils.gotoViewBigImageActivity(getActivity(), convertImageInfoToPicsItem(mAlbums), position, false, false);
            }
        });
    }

    private List<String> convertImageInfoToString(List<ImageInfo> infos){
        List<String> pics = new ArrayList<>();
        if(infos != null && infos.size() > 0){
            for(ImageInfo imageInfo : infos){
                pics.add(ImageUtils.getBigImageFullPath(imageInfo.filePath));
            }
        }
        return pics;
    }

    private ArrayList<PicsItem> convertImageInfoToPicsItem(List<ImageInfo> infos){
        ArrayList<PicsItem> pics = new ArrayList<PicsItem>();
        if(infos != null && infos.size() > 0){
            for(ImageInfo imageInfo : infos){
                PicsItem picsItem = new PicsItem();
                picsItem.image = ImageUtils.getBigImageFullPath(imageInfo.filePath);
                picsItem.id = imageInfo.fileId;
                pics.add(picsItem);
            }
        }
        return pics;
    }

    /**
     * 准备上传图片
     */
    private void prepareUploadImages(){
        if(mCameraPop != null) {
            mCameraPop.showMenu(plgridView);
        }
    }

    private CameraPop mCameraPop;
    private String mImagePath = null;
    private int mFileFiledId = -1;
    //初始化图片的菜单项
    private void initCameraPop(){
        mCameraPop = new CameraPop(this, new CameraPopListener() {
            @Override
            public void onCamreaClick(CameraOptions options) {
                options.setOpenType(OpenType.OPEN_CAMERA);
                mCameraPop.process();
            }

            @Override
            public void onPickClick(CameraOptions options) {
                options.setOpenType(OpenType.OPEN_GALLERY);
                mCameraPop.process();
            }

            @Override
            public void onDelClick() {

            }
        }, new CameraImageListener() {
            @Override
            public void onSelectedAsy(String imgPath) {
                if(imgPath != null){
                    mImagePath = imgPath;
                    doUploadImage();
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (mCameraPop != null) {
            mCameraPop.forResult(requestCode, resultCode, data);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 上传图片
     */
    private void doUploadImage(){
        showLoadingView("");
        NetManager.getInstance(getActivity().getApplicationContext()).doUploadImage(mImagePath, ImageUploadType.ALBUMS,
                new OnResponseListener<UploadFileInfoList>() {
                    @Override
                    public void onComplete(boolean isOK, UploadFileInfoList result, int errorCode, String errorMsg) {
                        hideLoadingView();
                        if (isOK && result != null && result.data != null && result.data.size() > 0) {
                            uploadAlbums(result.data.get(0).fileId);
                        } else {
                            LocalUtils.showToast(getActivity(), "图片上传失败！");
                        }
                    }

                    @Override
                    public void onInternError(int errorCode, String errorMessage) {
                        hideLoadingView();
                        LocalUtils.showToast(getActivity(), errorMessage);
                    }

                });
    }

    private void uploadAlbums(int fileFiledId){
        showLoadingView("图片上传中...");
        NetManager.getInstance(getActivity().getApplicationContext()).doUploadAlbum(String.valueOf(fileFiledId), new OnResponseListener<Boolean>() {
            @Override
            public void onComplete(boolean isOK, Boolean result, int errorCode, String errorMsg) {
                hideLoadingView();
                if(isOK && result){
                    startLoadData(true);
                } else {
                    LocalUtils.showToast(getActivity(),"图片上传失败！");
                }
            }

            @Override
            public void onInternError(int errorCode, String errorMessage) {
                hideLoadingView();
                LocalUtils.showToast(getActivity(), errorMessage);
            }
        });
    }
}
